package com.lkm.app_ui.ui;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.MBaseFragment;
import com.lkm.app_ui.MyApplication;
import com.lkm.app_ui.R;
import com.lkm.app_ui.RouterUINavigation;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.help.AppHelp;
import com.lkm.app_ui.help.PhoneInfoUtils;
import com.lkm.app_ui.help.QRCodeUtil;
import com.lkm.app_ui.m.fun.OnKeyNumberEvent;
import com.lkm.app_ui.view.choiceCard.ChoiceCard;
import com.lkm.comlib.Config;
import com.lkm.comlib.ui.BaseFragmentActivity;
import com.lkm.frame.otto.LinkBusCycleWrapper;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.task2.CTaskExecutor;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.frame.util.CycleHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.javatool.lang.RunnablePR;
import com.lkm.market2_0.m.steelyardserver.OnSteelyardKeyEvent;
import com.lkm.market2_0.m.steelyardstatus.StatusInfo;
import com.lkm.market2_0.m.steelyardstatus.SteelyardStatusManagerModule;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;



public class InfoFragment extends MBaseFragment implements View.OnClickListener {


    public static InfoFragment getInstance() {
        InfoFragment f = new InfoFragment();





        return f;
    }

    @Override
    protected int configLayoutResID() {
        return R.layout.fragment_info;
    }

    @Override
    protected boolean configIsLockKey() {
        return true;
    }

    private TextView tv_content;
    private TextView tv_content1;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tv_content = findViewById(R.id.tv_content);
        tv_content1 = findViewById(R.id.tv_content1);


        tv_content.setText("软件版本：" + AppHelp.getLocalVersionName());

        try {
            SteelyardStatusManagerModule statusManagerModule = (SteelyardStatusManagerModule) AppConst.getModuleManager().peekModule(SteelyardStatusManagerModule.class);

            StatusInfo statusInfo = statusManagerModule.getStatusInfoBySteelyardMac(RunTimeData.steelyardInfo.getSteelyardMac());

            tv_content.append("\n台秤软件版本：" + statusInfo.getVersion());

            tv_content.append("\n产品编码：" + statusInfo.getNumno());

            tv_content.append("\n秤号：" + RunTimeData.steelyardInfo.getB_id());

            tv_content.append("\n当前芯片码：" + RunTimeData.steelyardInfo.getSteelyardMac());


            try {
                String ccid = new PhoneInfoUtils(AppConst.getApplication()).getIccid();
                if (!StringHelp.isEmpty(ccid))
                tv_content.append("\nCCID：" + ccid);
            }catch (Exception e){}

//            String steelyardMac = AppConst.getApplication().getSharedPreferences("settingapp", Context.MODE_PRIVATE).getString("steelyardMac", "");


            tv_content.append("\n休眠时间：" + (RunTimeData.screenAutoOff>0?RunTimeData.screenAutoOff/1000f:RunTimeData.screenAutoOff));

            tv_content.append("\n打印机型号（默认新打印机）：" + RunTimeData.printerMode);
            tv_content.append("\n串口 ：" + RunTimeData.serialport);
        } catch (Exception e) {
        }
        try {
            tv_content1.setText("市场：" + RunTimeData.organizationInfo.getName());
            tv_content1.append("\n档口号：" + RunTimeData.steelyardInfo.getStallEntity().getStallNo());
            tv_content1.append("\n档口名称：" + RunTimeData.steelyardInfo.getStallEntity().getStallName());
            tv_content1.append("\n档口经营者：" + RunTimeData.steelyardInfo.getStallEntity().getName());
            tv_content1.append("\n经营者手机：" + RunTimeData.steelyardInfo.getStallEntity().getPhone());
        } catch (Exception e) {
        }

        try {
            ((TextView) findViewById(R.id.tv_content2)).setText(AppConst.deviceUncode);
        } catch (Exception e){ }
        CreateQR createQR = new  CreateQR();
        createQR.setParam(new Object[]{AppConst.deviceUncode});
        createQR.action();
        createQR.execTask();



        reOnKeyEvent();

        for (int i = 0; i < 10; i++) {
            View v = getView().findViewWithTag("fun_" + i);
            if(v!=null)
                v.setOnClickListener(this);
        }

    }

    private void reOnKeyEvent() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnSteelyardKeyEvent>() {
            @Override
            public Class<OnSteelyardKeyEvent> getBusEventClass() {
                return OnSteelyardKeyEvent.class;
            }

            @Override
            public void onReceiver(OnSteelyardKeyEvent data) {
                if (!data.isIntercepted()) {
                    data.setIntercepted(true);
                    int k = data.getKeyCode();
                    if(data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_FUN){
                        
                        k = OnSteelyardKeyEvent.KEYCODE_9;
                    }
                    try {
                        View v = getView().findViewWithTag("fun_" + k);
                        if (v != null)
                            onClick(v);
                    }catch (Exception e){}
                }

            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);















//                            View v = getView().findViewWithTag("fun_" + ((int)data.getNumber()));






//        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }

    @Override
    public void onClick(View v) {
        if ("fun_0".equals(v.getTag())) {

            RouterUINavigation.getInstance().showWifi((BaseFragmentActivity) getActivity(),false);
            RouterUINavigation.getInstance().dismiss(InfoFragment.this);
        } else if ("fun_9".equals(v.getTag())) {
            RouterUINavigation.getInstance().dismiss(InfoFragment.this);
        }
    }

    protected class CreateQR extends TaskAdapter<Object[], Void, Bitmap> {

        public CreateQR() {
            super(new CTaskExecutor<Object[], Void, Bitmap>(Config.getTaskExecutor(), Looper.getMainLooper()), CreateQR.class.getName(), MyApplication.getInstance().getTaskManager2());
        }


        @Override
        public void doExecuting(Object[] param) {
            super.doExecuting(param);
            mTaskExecutor.executor(new RunnablePR<Object[], Void>() {
                @Override
                public Void run(Object[] objects) {
                    complete(onExecuting(objects));
                    return null;
                }
            }, param);
        }

        public Bitmap onExecuting(Object[] param) {

            int ip = -1;
            String uid = (String) param[++ip];


            String bid = "", bid_ = "" , bon = "";
            if(RunTimeData.steelyardInfo!=null) {
                bid = RunTimeData.steelyardInfo.getB_id();
                bon = RunTimeData.steelyardInfo.steelyardMac;

                StatusInfo statusInfo = null;
                SteelyardStatusManagerModule statusManagerModule = (SteelyardStatusManagerModule) AppConst.getModuleManager().peekModule(SteelyardStatusManagerModule.class);
                if (statusManagerModule != null ) {
                    statusInfo = statusManagerModule.getStatusInfoBySteelyardMac(RunTimeData.steelyardInfo.getSteelyardMac());
                }
                if(statusInfo != null){
                    bid_ = statusInfo.getNumno();
                }
            }

            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("uid", uid);
            jsonObject.addProperty("bid", bid);
            jsonObject.addProperty("bid_", bid_);
            jsonObject.addProperty("bon", bon);
            String s = "";
            try{
                s = jsonObject.toString();
            }catch (Error e){}

            Bitmap bitmap = QRCodeUtil.createImage(s, 200, 200);
            return bitmap;//ResponEntity.fromJson(Api.order_add(c,datas,this),AddOrderResult.class);
        }

        @Override
        public void onFinish(Bitmap bitmap) {
            super.onFinish(bitmap);
            if (isExit()) return;

            try {
                ImageView img_qr = (ImageView) findViewById(R.id.img_qr);
                img_qr.setImageBitmap(bitmap);
            }catch (Exception e){}

        }
    }

}
